package com.study.guide.codec.Marshalling;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class TimeServerHandler extends SimpleChannelInboundHandler<Object> {
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		// 经过解码器处理 ，接收到的请求消息(msg)已经被自动解码为Request对象，可以直接使用。
		Request req = (Request) msg;
		System.out.println("--- Service accept client : [" + req.toString() + "]");
		// 对订购者的用户名进行合法性校验，校验通过后打印订购请求消息，构造订购成功应答消息立即发送给客户端。
		ChannelFuture channelFuture = ctx.writeAndFlush(resp(req.getSubReqID()));


	}

	private Response resp(int subReqID) {
		Response resp = new Response();
		resp.setSubReqID(subReqID);
		resp.setRespCode(0);
		resp.setDesc("Netty book order succeed, 3 days later, sent to the designated address");
		return resp;
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}

}
